<?php
if (!defined('INC')) include('../includes/definer.php');
if (!defined('BOOTSTRAP')) include(INC.'admin/php/bootstrap.php');

/*
 * espacio (filtrado)
 * esquema (filtrado)
 * esquema link (filtrado)
 * vista previa esquema (todas las especies)
 * especie link (todas las especies)
 */


if (isset($_SESSION['userSelection']) || isset($_GET['sol'])) {
    $userSelection = isset($_SESSION['userSelection'])?$_SESSION['userSelection']:$_GET;
    $q = Doctrine_Query::create()
            ->select('e.slug, e.nombre, e.denominacion, i.src as imagen')
            ->from('Especie e')
            ->leftJoin('e.imagen as i')
            ->innerJoin('e.espacios as esp WITH esp.slug = ?', $userSelection['espacio'])
            ->innerJoin('esp.dimension as d WITH d.id = ?', $userSelection['dimension'])
            ->innerJoin('e.zonas as z WITH z.id = ?', $userSelection['zona'])
            //->innerJoin('e.dimensiones as d WITH d.id = ?', $userSelection['dimension'])
            ->innerJoin('e.soles as s WITH s.id = ?', $userSelection['sol'])
            ->innerJoin('e.regiones as r')
            ->whereIn('r.id', $userSelection['regiones'])
            ->orderBy('e.nombre')
    ;
    if (isset($_GET['esquema'])) { //esquema, esquema link
        $nativaListTitle = 'Esquema '.Doctrine::getTable('esquema')->findOneBySlug($_GET['esquema'])->value;
        $especies = $q->innerJoin('e.esquemas as esq WITH esq.slug = ?', $_GET['esquema'])->execute(array(), Doctrine::HYDRATE_ARRAY);
        if (isset($_GET['sol'])) {
            $back = URL; //esquema link
        }
    } else{ //espacio
        $nativaListTitle = Doctrine::getTable('espacio')->findOneBySlug($userSelection['espacio'])->value;
        $especies = (count($esquemas))?$q->execute(array(), Doctrine::HYDRATE_ARRAY):array();
    }
} else {       
    $q = Doctrine_Query::create()
        ->select('e.slug, e.nombre, e.denominacion, i.src as imagen')
        ->from('Especie e')
        ->innerJoin('e.imagen i');
    if (isset($_GET['especie'])) { //especie link
        $especies = $q->orderBy('e.slug = "'.$_GET['especie'].'" desc, e.nombre')->execute(array(), Doctrine::HYDRATE_ARRAY);
    } else { //vista previa esquema
        $especies = $q->innerJoin('e.esquemas as esq WITH esq.slug = ?', $_GET['esquema'])->orderBy('e.nombre')->execute(array(), Doctrine::HYDRATE_ARRAY);
    }
    $nativaListTitle = 'Listado general de especies';
    $back = URL;
}

$html = file_get_contents(INC.'tpl/listado-especies.tpl');
$natviaListItemTpl = file_get_contents(INC.'tpl/nativa-list-item.tpl');
include(INC.'php/replacers/listadoEspecies.replacer.php');
echo($html);
?>